#include "pointpairlistplus.h"
#include "util.h"

bool PointPairListPlus::serialize(QDomElement& elem, QDomDocument& doc) const {
    elem.setTagName(QString("region").append(QString::number(myPED->pointNumber)));
    if (myPED->myStep == 0) {
        return true;
    }
    Util::serializeUshort(elem, doc, "peak", myPED->myStep);
    Util::serializeUshort(elem, doc, "col", myPED->isFirstCollector? 1: 2);
    Util::serializeUshort(elem, doc, "iteration", myPED->myIterations);
    Util::serializeUshort(elem, doc, "width", myPED->myWidth);
    Util::serializeFloat(elem, doc, "error", myPED->prec);
    Util::serializeString(elem, doc, "comment", myPED->myComment);
    Util::serializeBool(elem, doc, "use", myPED->usethis);
    int size = dataSize();
    for (int i = 0; i < size; ++i) {
        QDomElement pointElement = doc.createElement("p");
        Util::serializeUshort(pointElement, doc, "s", x(i));
        Util::serializeUshort(pointElement, doc, "c", y(i));
        elem.appendChild(pointElement);
    }
    return true;
}

bool PointPairListPlus::deserialize(const QDomElement& elem, unsigned short i) {
    myPED->pointNumber = i;

    if (!Util::deserializeUshort(elem, "peak", myPED->myStep)) {
        // empty peak
        myPED->myStep = 0;
        return true;
    }
    unsigned short col;
    if (!Util::deserializeUshort(elem, "col", col)) return false;
    myPED->isFirstCollector = (col == 1);
    if (!Util::deserializeUshort(elem, "iteration", myPED->myIterations)) return false;
    if (!Util::deserializeUshort(elem, "width", myPED->myWidth)) return false;
    if (!Util::deserializeFloat(elem, "error", myPED->prec)) return false;
    if (!Util::deserializeString(elem, "comment", myPED->myComment)) return false;
    if (!Util::deserializeBool(elem, "use", myPED->usethis)) return false;

    QVector<double> xs;
    QVector<double> ys;

    QDomNodeList dnl = elem.elementsByTagName("p");
    for (int i = 0; i < dnl.size(); ++i) {
        QDomElement de = dnl.at(i).toElement();
        if (de.isNull()) {
            return false;
        }

        unsigned short step;
        if (!Util::deserializeUshort(de, "s", step)) return false;

        unsigned short count;
        if (!Util::deserializeUshort(de, "c", count)) return false;

        xs.append(step);
        ys.append(count);
    }
    setData(xs, ys);
    setTitle(QString("[%1] %2").arg(myPED->pointNumber).arg(myPED->myComment));
    return true;
}
